import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args)throws Exception{
        ServerSocket server = new ServerSocket(2000);

        System.out.println("服务器准备就绪");

        System.out.println("服务器信息："+server.getInetAddress()+" P: "+server.getLocalPort());

        //等待客户端连接
        for (;;) {
            //得到客户端
            Socket client = server.accept();
            ClientHandler clientHandler = new ClientHandler(client);
            clientHandler.start();
        }
    }

    private static class ClientHandler extends Thread{

        private Socket socket;
        private boolean flag = true;
        ClientHandler(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            super.run();
            System.out.println("新客户端连接了："+socket.getInetAddress()+" P :"+socket.getPort());

            try{
                //得到打印流用于数据输出
                PrintStream socketOut = new PrintStream(socket.getOutputStream());
                //得到输入流用于接收数据
                BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                do{

                    String str = socketInput.readLine();
                    if("bye".equalsIgnoreCase(str)){
                        flag = false;
                        socketOut.println("bye");
                    }else{
                        System.out.println(str);
                        socketOut.println("回送："+str.length());
                    }


                }while(flag);

                socketInput.close();
                socketOut.close();


            }catch (Exception e){
                System.out.println("连接异常");
            }finally {
                try{
                    socket.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            System.out.println("客户端已退出:"+socket.getInetAddress()+" P :"+socket.getPort());

        }
    }

}
